#include "MagTwin.h"
#include "./ui_MagTwin.h"
#include <QDebug>
#include <QFileDialog>
#include <QPushButton>
#include <QGraphicsLineItem>
#include <QMessageBox>
#include <QInputDialog>
#include <QString>
#include <numeric>
#include <QScrollBar>
#include "MagGraphicsView.h"
#include "MagCAD.h"

MagTwin::MagTwin(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MagTwin)
{
    initUI();  //  UI界面初始化
    loadingActions();  //  设置信号槽关系
    maglog.setInfoLog("程序启动成功！");  //写入日志信息
    updateLog();  //更新显示日志信息于窗口
}

MagTwin::~MagTwin()
{
    maglog.exportLog("magtwin.log");  //将日志写入文件
    delete ui;
    ui = nullptr;
}

void MagTwin::initUI(){
    ui->setupUi(this);
    this->setWindowState(Qt::WindowMaximized); // 默认软件启动后全屏显示
    ui->MainWindowSplitter->setSizes({MainWindowSplitterScale});
    ui->ShowWindowSplitter->setSizes({ShowWindowSplitterScale});
    ui->TBarMesh->layout()->setAlignment(Qt::AlignLeft);
}

void MagTwin::loadingActions(){
    connect(ui->ImportMeshBtn, &QPushButton::clicked, this, [=](){  // 导入Gmsh网格
        mesh->clearMesh();
        QString filePath = QFileDialog::getOpenFileName(nullptr, QObject::tr("选择文件"), "", QObject::tr("所有文件 (*.*)"));
        mesh->getMesh(filePath.toStdString());
        maglog.setInfoLog("导入Gmsh网格成功！");
        updateLog();
    });
    connect(ui->ExportMeshBtn, &QPushButton::clicked, this, [=](){  // 导出Gmsh网格为mat格式
        std::string filename2 = "G:/mag-twin/src/bin/example.mat";
        MeshOutput* meshoutput = new MeshOutput();
        meshoutput->MeshtoMat(filename2, *mesh);
        maglog.setInfoLog("导入网格为mat格式成功！");
        updateLog();
    });
    // 添加一个按钮
    // QPushButton *resizeButton = new QPushButton("Resize", ui->ShowGraphics); // 创建一个按钮
    // resizeButton->setGeometry(10, 30, 80, 30); // 设置按钮位置和大小
    // connect(resizeButton, &QPushButton::clicked, this, [=](){  // 调整画布大小
    //     this->ui->ShowGraphics->resizeGraphics(ui->ShowGraphics);
    // });
    connect(ui->ShowMeshBtn, &QPushButton::clicked, this, [=](){  // 显示网格
        ui->ShowCAD->showMesh(*mesh);
        // this->ui->ShowGraphics->showMesh(*mesh);
        // this->ui->ShowGraphics->resizeGraphics(ui->ShowGraphics);
        maglog.setInfoLog("显示网格成功！");
        updateLog();
    });

    connect(ui->MeshInfBtn, &QPushButton::clicked, [&]() {
        // 当按钮被点击时，显示提示信息
        uint numNodes = mesh->getnumNodes();
        uint numElements = mesh->getnumElements();
        QString meshInf = QString("网格结点总数: %1\n单元总数: %2").arg(numNodes).arg(numElements);
        QMessageBox::information(this, "网格信息", meshInf);
    });

    // connect(ui->ShowPtMeshBtn, &QPushButton::clicked, [&](){
    //     bool ok;
    //     QString text = QInputDialog::getText(this, tr("输入节点编号"), tr("节点编号:"), QLineEdit::Normal, "", &ok);
    //     if (ok && !text.isEmpty()) {
    //         std::vector<std::vector<double>> coord = mesh->getcoord();
    //         uint index = text.toUInt();
    //         QPointF point{coord[index][1], coord[index][2]};
    //         QList<QPointF> points{point};
    //         ui->ShowGraphics->addPoint(points);

    //         double rec{10};
    //         ui->ShowGraphics->fitInView(points[0].rx()-10, points[0].ry()-rec, 2*rec, 2*rec, Qt::KeepAspectRatio);

    //     }
    // });

    // connect(ui->ShowPtMeshBtn, &QPushButton::clicked, [&](){
    //     bool ok;
    //     QString text = QInputDialog::getText(this, tr("输入线单元编号"), tr("线单元编号:"), QLineEdit::Normal, "", &ok);
    //     if (ok && !text.isEmpty()) {
    //         std::vector<std::vector<double>> coord = mesh->getcoord();
    //         std::vector<std::vector<uint>> line = mesh->getelement_L();
    //         uint index = text.toUInt();

    //         QPointF point1{coord[line[index][2]][1], coord[line[index][2]][2]};
    //         QPointF point2{coord[line[index][3]][1], coord[line[index][3]][2]};
    //         QList<QLineF> lines;
    //         lines.push_back({point1, point2});
    //         ui->ShowGraphics->addLine(lines);
    //         // 自动调整视图大小以适应场景
    //         QPointF startPoint = point1;
    //         QPointF endPoint = point2;

    //         // Calculate the bounding rectangle of the line
    //         QRectF lineBoundingRect(startPoint, endPoint);
    //         ui->ShowGraphics->fitInView(lineBoundingRect, Qt::KeepAspectRatio);
    //     }
    // });

    connect(ui->MainWindowSplitter, &QSplitter::splitterMoved, this, [&](){
        QList<int> scale = ui->MainWindowSplitter->sizes();
        if(scale[0] == 0){
            ui->ShowSideBar->setText("显示侧边栏");
        }else{
            ui->ShowSideBar->setText("隐藏侧边栏");
        }
    });
    connect(ui->ShowSideBar, &QAction::triggered, this, [&](){

        QList<int> scale = ui->MainWindowSplitter->sizes();
        if(scale[0] == 0){
            ui->MainWindowSplitter->setSizes({MainWindowSplitterScale});
            ui->ShowSideBar->setText("隐藏侧边栏");
        }else{
            ui->MainWindowSplitter->setSizes({0, 1});
            ui->ShowSideBar->setText("显示侧边栏");
        }

    });
}



void MagTwin::updateLog(){
    std::vector<std::string> contents = maglog.getAllLog();
    std::string str = std::accumulate(contents.begin(), contents.end(), std::string());
    ui->ShowProgress->setPlainText(QString::fromStdString(str));
    QScrollBar *verticalScrollBar = ui->ShowProgress->verticalScrollBar();
    // 将滚动条位置设置为最大值
    verticalScrollBar->setValue(verticalScrollBar->maximum());
}


